package com.haiertvbic.tvnow.network;

import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.apache.http.conn.ConnectTimeoutException;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.haiertvbic.tvnow.util.SLog;

public class NetUtil {
	private static final String TAG = "NetUtil";

	/**
	 * 判断互联网是否可用，若可用返回true
	 * 
	 * @return
	 */
	public static boolean isNetAvailable() {
		boolean isnet = false;
		HttpURLConnection conn = null;
		try {
			String url = "http://www.baidu.com";
			URL imageUrl = new URL(url);
			conn = (HttpURLConnection) imageUrl.openConnection();
			conn.setConnectTimeout(1000);
			conn.setReadTimeout(1000);
			// conn.setRequestMethod("POST");
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() == 200) {
				// InputStream inSrteam = conn.getInputStream();
				isnet = true;
				SLog.d(TAG, "the net  available");
			} else {
				isnet = false;
				SLog.d(TAG, "the net not available");
			}
			// SocketTimeoutException
			// org.apache.http.conn.ConnectTimeoutException:
			// HttpHostConnectException
			// UnknownHostException
		} catch (SocketTimeoutException e) {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
			isnet = false;
		} catch (ConnectTimeoutException e) {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
			isnet = false;
		} catch (Exception e) {
			SLog.i(TAG, e.toString());
			SLog.d(TAG, "the net not available");
			isnet = false;
		}
		return isnet;
	}

	/**
	 * 判断网络连接是否可用
	 * 
	 * @returns 若可用返回true
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		if (info != null) {
			return info.isAvailable();
			// return info.isConnected();
		} else {
			return false;
		}
	}

	public static boolean getNetworkInfo(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
